package com.boe.csb.web.controller.csb;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.csb.console.sdk.Result;
import com.alibaba.csb.sdk.HttpCallerException;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.boe.csb.core.common.CsbConstants;
import com.boe.csb.core.common.csbsdk.HttpCaller;
import com.boe.csb.core.common.exception.CSBErrorCode;
import com.boe.csb.core.common.exception.CSBException;
import com.boe.csb.core.common.status.CertificationStatus;
import com.boe.csb.core.common.utils.MailTemplate;
import com.boe.csb.core.common.utils.PublishParamChecker;
import com.boe.csb.core.entity.UserInfo;
import com.boe.csb.core.entity.po.BoeUser;
import com.boe.csb.core.service.csb.CsbManagerApiService;
import com.boe.csb.core.service.user.BoeUserService;
import com.boe.csb.web.controller.BaseController;
import com.boe.csb.web.controller.base.BoeUserController;
import com.boe.csb.web.model.ResultModel;

/**
 * Created by tianxiang.luo on 16/11/27.
 */

@RequestMapping("/api/manager/service")
@RestController
public class CsbManagerServiceController extends BaseController {

    private Logger logger  = LoggerFactory.getLogger(CsbManagerServiceController.class);

    @Autowired
    private BoeUserService boeUserService;

    @Autowired
    private CsbManagerApiService csbManagerApiService;
   

    /**
     * 发布服务
     */
    @RequestMapping(value = "/publish", method = RequestMethod.POST)
    public ResultModel pushService(HttpSession session, @RequestBody JSONObject data) throws IOException {
        PublishParamChecker.checkJson(data);
        UserInfo userInfo = fetchUserInfo(session);
        csbManagerApiService.publishService(String.valueOf(userInfo.getUserId()), JSON.toJSONString(data));
        String apiName = data.getString("serviceName");
        csbManagerApiService.sendAdminUserMail(MailTemplate.RELEASE, apiName,userInfo.getUserName()+"-"+userInfo.getUserId());
        return ResultModel.success(null);
    }


    /**
     * 已经发布的服务
     *
     * @return
     */
    @RequestMapping(value = "/own", method = RequestMethod.GET)
    public ResultModel<Result> ownServicesList(HttpSession session, @RequestParam int pageNum,
                                               @RequestParam(required = false) String serviceName,
                                               @RequestParam(required = false) String alias) {
        String userId = fetchUserId(session);
        return ResultModel.success(csbManagerApiService.ownPublishedService(userId, pageNum, serviceName, alias));
    }

    /**
     * 删除自己发布的服务
     *
     * @return
     */
    @RequestMapping(value = "/delete/own", method = RequestMethod.POST)
    public ResultModel<Result> deleteOwnServices(HttpSession httpSession, @RequestParam Long serviceId, @RequestParam String serviceName) {
        UserInfo userInfo = (UserInfo) httpSession.getAttribute(BoeUserController.USER_KEY);
        Long userId = userInfo.getUserId();
        return ResultModel.success(csbManagerApiService.deleteOwnServices(userId, serviceId, serviceName));
    }

    /**
     * 查询服务的详情
     *
     * @param serviceId
     * @return
     */
    @RequestMapping(value = "query", method = RequestMethod.GET)
    public ResultModel<Result> queryApiInfo(HttpSession session, @RequestParam Long serviceId) {
        String userId = fetchUserId(session);
        return ResultModel.success(csbManagerApiService.findSingleService(userId, serviceId));
    }

    /**
     * 服务的状态
     */
    @RequestMapping(value = "status", method = RequestMethod.POST)
    public ResultModel<JSONObject> updateStatus(HttpSession session, @RequestParam List<Long> serviceId, @RequestParam String status) {
        String userId = fetchUserId(session);
        return ResultModel.success(csbManagerApiService.updateServiceStatus(userId, serviceId, status).getData());
    }

    /**
     * 获取服务的json(调用服务的调试用)
     */
    @RequestMapping(value = "/param")
    public ResultModel<JSONObject> queryServiceParam(Long serviceId) {
        return ResultModel.success(csbManagerApiService.queryServiceParam(serviceId));
    }

    /**
     * 调用调试
     *
     *
     * {
     * params:{
     *  "type":"s",
     *  "name":"louie"
     * },
     * apiName:"httptest",
     * version:"1.0.0",
     * method:
     * }
     */
    @RequestMapping(value = "/debug/service", method = RequestMethod.POST)
    public ResultModel<JSONObject> debugService(HttpSession session, @RequestBody JSONObject data) throws HttpCallerException {

        String userId = fetchUserId(session);
        String result;
        BoeUser boeUser = boeUserService.findBoeUser(userId);
        if (!CertificationStatus.ALLOW.getStatus().equals(boeUser.getAuditStatus())) {
            throw new CSBException(CSBErrorCode.NO_AUTH, "");
        }
        String ak = boeUser.getAk();
        String sk = boeUser.getSk();
        String requestURL = CsbConstants.CSB_API_ADDRESS;
        String API_NAME = (String) data.remove("apiName");
        String version = (String) data.remove("version");
        String method = (String) data.remove("method");
        Map<String, String> paramsMap = new HashMap<>();
        JSONObject params = data.getJSONObject("params");
        for (String key : params.keySet()) {
            paramsMap.put(key, params.getString(key));
        }
        logger.debug("开始请求sdk,url=" + requestURL + ",apiName=" + API_NAME + ",version=" + version + ",paramsMap=" + params.toString());
        if ("POST".equalsIgnoreCase(method)) {
            result = HttpCaller.doPost(requestURL, API_NAME, version, paramsMap, ak, sk);
        } else {
            result = HttpCaller.doGet(requestURL, API_NAME, version, paramsMap, ak, sk);
        }
//        result = HttpCaller.changeCharset(result);
        JSONObject debug = new JSONObject( );
        debug.put("Request",JSONObject.toJSONString(data));
        debug.put("Response", result);
        return ResultModel.success(debug);
    }

}
